/**
 * 跨平台应用跳转工具
 * @param {Object} options - 跳转配置
 * @param {string} options.androidPname - 安卓应用包名 (如: com.taobao.taobao)
 * @param {string|Object} options.ios - iOS 应用配置
 * @param {string} options.ios.scheme - iOS 应用 URL Scheme (如: taobao://)
 * @param {string} [options.ios.appId] - iOS 应用 App Store ID (可选，用于跳转 App Store)
 * @param {function} [options.onSuccess] - 跳转成功回调
 * @param {function} [options.onFail] - 跳转失败回调
 * @param {function} [options.onNotInstalled] - 应用未安装回调
 * @example
 *   // 跳转淘宝
 *   launchApp({
 *     androidPname: "com.taobao.taobao",
 *     ios: "taobao://",
 *     onSuccess: function() {
 *       console.log("Launch taobao success");
 *     },
 *     onFail: function(e) {
 *       console.error(`Launch taobao failed: ${e.message}`);
 *     },
 *     onNotInstalled: function() {
 *       console.error("Taobao not installed");
 *     }
 *   });
 *
 *   // 跳转京东
 *   launchApp({
 *     androidPname: "com.jingdong.app.mall",
 *     ios: {
 *       scheme: "openApp.jdmobile://",
 *       appId: "414245413",
 *     },
 *     onSuccess: function() {
 *       console.log("Launch jdmobile success");
 *     },
 *     onFail: function(e) {
 *       console.error(`Launch jdmobile failed: ${e.message}`);
 *     },
 *     onNotInstalled: function() {
 *       console.error("Jdmobile not installed");
 *     }
 *   });
 *
 *
 */
function launchApp(options) {
  // 参数验证
  if (!options) {
    throw new Error("Missing required parameter: options");
  }

  const { androidPname, ios, onSuccess, onFail, onNotInstalled } = options;

  // 验证 iOS 参数
  let iosScheme, iosAppId;
  if (ios) {
    if (typeof ios === "string") {
      // 兼容旧格式：直接传入 scheme
      iosScheme = ios;
    } else if (typeof ios === "object" && ios.scheme) {
      // 新格式：{ scheme, appId }
      iosScheme = ios.scheme;
      iosAppId = ios.appId;
    }
  }

  if (!androidPname && !iosScheme) {
    throw new Error("Missing required parameters: androidPname or ios.scheme");
  }

  // 判断平台
  if (plus.os.name === "Android") {
    // 安卓平台使用包名跳转
    launchAndroidApp(androidPname, onSuccess, onFail, onNotInstalled);
  } else if (plus.os.name === "iOS") {
    // iOS平台使用URL Scheme跳转
    launchIOSApp(iosScheme, iosAppId, onSuccess, onFail, onNotInstalled);
  } else {
    const errorMsg = `Unsupported platform: ${plus.os.name}`;
    console.error(errorMsg);
    onFail && onFail(new Error(errorMsg));
  }
}

/**
 * 安卓平台应用跳转
 */
function launchAndroidApp(pname, onSuccess, onFail, onNotInstalled) {
  if (
    plus.runtime.isApplicationExist({
      pname,
    })
  ) {
    // 应用存在，尝试跳转
    plus.runtime.launchApplication(
      { pname },
      function (e) {
        console.error(`Launch Android app failed: ${e.message}`);
        onFail && onFail(e);
      },
      function () {
        console.log("Launch Android app success");
        onSuccess && onSuccess();
      }
    );
  } else {
    // 应用不存在
    console.error(`Android app not installed: ${pname}`);
    onNotInstalled && onNotInstalled();
  }
}

/**
 * iOS平台应用跳转
 */
function launchIOSApp(scheme, appId, onSuccess, onFail, onNotInstalled) {
  if (plus.runtime.isApplicationExist({ action: scheme })) {
    // 应用存在，尝试跳转
    plus.runtime.launchApplication(
      { action: scheme },
      function (e) {
        console.error(`Launch iOS app failed: ${e.message}`);
        onFail && onFail(e);
      },
      function () {
        console.log("Launch iOS app success");
        onSuccess && onSuccess();
      }
    );
  } else {
    // 应用不存在
    console.error(`iOS app not installed: ${scheme}`);

    // 如果提供了App Store ID，尝试跳转到App Store
    if (appId) {
      plus.runtime.launchApplication(
        { action: `itms-apps://itunes.apple.com/app/id${appId}` },
        function (e) {
          console.error(`Launch App Store failed: ${e.message}`);
          onFail && onFail(e);
        },
        function () {
          console.log("Launch App Store success");
          onSuccess && onSuccess();
        }
      );
    } else {
      onNotInstalled && onNotInstalled();
    }
  }
}

// 常见应用跳转配置
const AppConfig = [
  {
    name: "淘宝",
    androidPname: "com.taobao.taobao",
    ios: {
      scheme: "taobao://",
      appId: "387682726",
    },
    downloadUrl: {
      android: "https://a.app.qq.com/o/simple.jsp?pkgname=com.taobao.taobao",
      ios: "https://apps.apple.com/cn/app/id387682726",
    },
  },
  {
    name: "京东",
    androidPname: "com.jingdong.app.mall",
    ios: {
      scheme: "openApp.jdmobile://",
      appId: "414245413",
    },
    downloadUrl: {
      android:
        "https://a.app.qq.com/o/simple.jsp?pkgname=com.jingdong.app.mall",
      ios: "https://apps.apple.com/cn/app/id414245413",
    },
  },
  {
    name: "拼多多",
    androidPname: "com.xunmeng.pinduoduo",
    ios: {
      scheme: "pinduoduo://",
      appId: "839387267",
    },
    downloadUrl: {
      android:
        "https://a.app.qq.com/o/simple.jsp?pkgname=com.xunmeng.pinduoduo",
      ios: "https://apps.apple.com/cn/app/id839387267",
    },
  },
];

export { launchApp, AppConfig };
